<?php

require_once 'google/appengine/api/cloud_storage/CloudStorageTools.php';

use google\appengine\api\cloud_storage\CloudStorageTools;

/* * ****************************************************************************
 * controllers\CustomerController
 * 
 * author  Laureta Xhaferaj
 * email   laureta@first.al
 * 
 * @function index
 * @function create
 * @function store
 * @function show
 * @function edit
 * @function update
 * @function destroy
 * @function customer_pic
 * @function upload_pic
 * *************************************************************************** */

class CustomerController extends \BaseController {

    /**
     * Display a table with customers info
     *
     * @return array
     */
    public function index() {
        $values = DB::select('select * from customers');
        return View::make('pages.customers', array(
                    'values' => $values,
        ));
    }

    /**
     * Form to create e new customer.
     *
     * @return response
     */
    public function create() {
        return View::make('pages.customer_create');
    }

    /**
     * Store a new customer.
     *
     * @return Response
     */
    public function store() {
   
        Input::flash();
        $data = [
            "errors" => null
        ];
        $attributes = array(
            'drfirstname' => Lang::get('customer.drfirstname'),
            'drlastname' => Lang::get('customer.drlastname'),
            'cardnr' => Lang::get('customer.cardnr'),
            'drliccat' => Lang::get('customer.drliccat'),
            'drpasportid' => Lang::get('customer.drpasportid'),
            'DREMAIL' => Lang::get('customer.DREMAIL'),
        );
        $rules = array(
            "drfirstname" => "required",
            "drlastname" => "required",
            "cardnr" => "required",
            "drliccat" => "required",
            "drpasportid" => "required|unique:customers,drpasportid",
            "DREMAIL" => "required",
        );
        $validation = Validator::make(Input::all(), $rules, array(), $attributes);
        if ($validation->passes()) {
            $data = new Customer;
            $data->drfirstname = Input::get('drfirstname');
            $data->drlastname = Input::get('drlastname');
            $data->drbdate = Input::get('drbdate');
            $data->draddress = Input::get('draddress');
            $data->drhphone = Input::get('drhphone');
            $data->drcountry = Input::get('drcountry');
            $data->drlicnr = Input::get('drlicnr');
            $data->cardnr = Input::get('cardnr');
            $data->drplace = Input::get('drplace');
            $data->drliccat = Input::get('drliccat');
            $data->drpasportid = Input::get('drpasportid');
            $data->DREMAIL = Input::get('DREMAIL');
            $data->drcity = Input::get('drcity');
            $data->nrPikeve = Input::get('nrPikeve');
            $data->save();
            // redirect
            return Response::json(["redirect_to" => "/"]);
        } else {
            if (Request::ajax()) {
                $response_values = array(
                    'validation_failed' => 1,
                    'errors' => $validation->errors()->toArray(),
                );
                return Response::json($response_values);
            } else {
                $data['errors'] = $validation->errors();
                return View::make('pages.customer_create', $data);
            }
        }
    }

    /**
     * Display the specified customer info.
     *
     * @param  int  $id
     * @return array
     */
    public function show($id) {
        $values = DB::select('select * from customers where drpasportid=?', array($id));

        $object_image_file = DB::select('select picture from customers'
                        . ' where drpasportid=?', array($id));

        $object_patent_file = DB::select('select patent_pic from customers'
                        . ' where drpasportid=?', array($id));

        if ($object_image_file[0]->picture != NULL) {
            $image = CloudStorageTools::getImageServingUrl($object_image_file[0]->picture, ["secure_url" => true]);
        } else {
            $image = CloudStorageTools::getImageServingUrl('gs://customer_pic/noavatar.png', ["secure_url" => true]);
        }
        if ($object_patent_file[0]->patent_pic != NULL) {
            $patenta = CloudStorageTools::getImageServingUrl($object_patent_file[0]->patent_pic, ["secure_url" => true]);
        } else {
            $patenta = CloudStorageTools::getImageServingUrl('gs://customer_pic/noavatar.png', ["secure_url" => true]);
        }





        return View::make('pages.customer_data', array(
                    'values' => $values,
                    'image' => $image,
                    'patent' => $patenta
        ));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id) {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id) {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id) {
        //
    }

    /**
     * Form to upload customer's pics.
     *
     * @param  int  $id
     * @return Response
     */
    public function customer_pic($id) {
        $options = ['gs_bucket_name' => 'national-test.appspot.com'];
        $upload_url = CloudStorageTools::createUploadUrl('/upload_pic', $options);
        $values = DB::select('select * from customers where drpasportid=?', array($id));
        return View::make('pages.customer_pic', array(
                    'values' => $values,
                    'upload_url' => $upload_url
        ));
    }

    /**
     * Upload picture of a customer.
     *
     * @return Response
     */
    public function upload_pic() {
        if (Input::hasFile('uploaded_files')) {
            $drpasportid = Input::get('id_value');
            $options = ['gs' => ['Content-Type' => 'text/plain']];
            $random = str_random(10);
            $ctx = stream_context_create($options);
            if (false == rename($_FILES['uploaded_files']['tmp_name'], 'gs://customer_pic/' . $random . $drpasportid, $ctx)) {
                die('Could not rename.');
            }
            $data = Customer::find($drpasportid);
            $data->picture = 'gs://customer_pic/' . $random . $drpasportid;
            $data->save();

            return Redirect::to('customer/' . $drpasportid);
        } else {
            $id = Input::get('id_value');
            return Redirect::to('customer_pic/' . $id)->with('message', Lang::get('messages.upload_fail'));
        }
    }

    public function customer_patent($id) {
        $options = ['gs_bucket_name' => 'national-test.appspot.com'];
        $upload_url = CloudStorageTools::createUploadUrl('/upload_patent', $options);
        $values = DB::select('select * from customers where drpasportid=?', array($id));
        return View::make('pages.customer_patent', array(
                    'values' => $values,
                    'upload_url' => $upload_url
        ));
    }
    
       /**
     * Upload picture of a customer.
     *
     * @return Response
     */
    public function upload_patent() {
        if (Input::hasFile('uploaded_files')) {
            $drpasportid = Input::get('id_value');
            $options = ['gs' => ['Content-Type' => 'text/plain']];
            $random = str_random(10);
            $ctx = stream_context_create($options);
            if (false == rename($_FILES['uploaded_files']['tmp_name'], 'gs://customer_patent/' . $random . $drpasportid, $ctx)) {
                die('Could not rename.');
            }
            $data = Customer::find($drpasportid);
            $data->patent_pic = 'gs://customer_patent/' . $random . $drpasportid;
            $data->save();

            return Redirect::to('customer/' . $drpasportid);
        } else {
            $id = Input::get('id_value');
            return Redirect::to('customer_patent/' . $id)->with('message', Lang::get('messages.upload_fail'));
        }
    }

}
